package com.hello.common.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component(value = "myMetaObjectHandler")
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long loginId = null;
        if (StpUtil.isLogin()) {
            loginId = StpUtil.getLoginIdAsLong();
        }
        if (loginId == null) {
            loginId = 0L;
        }


        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now());
        // 假设 UserPO 中有 getUserId() 方法来获取 userId
        if (loginId != null) {
            this.strictInsertFill(metaObject, "createBy", Long.class, loginId);
            this.strictInsertFill(metaObject, "modifyBy", Long.class, loginId);
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        Long loginId = StpUtil.getLoginIdAsLong();
        this.strictUpdateFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now());
        if (loginId != null) {
            this.strictInsertFill(metaObject, "modifyBy", Long.class, loginId);
        }
    }

}
